import router from '@/router/index'
import { showMessage } from './composables/util'
import { getToken } from '@/composables/cookie'
import { showPageLoading, hidePageLoading } from '@/composables/util'
import { useBlogSettingsStore } from '@/stores/blogsettings'

// 全局路由前置守卫
router.beforeEach((to, from, next) => {
    // to and from are both route objects. must call `next`.
    console.log('==> 全局路由前置守卫')

    // 界面加载 Loading
    showPageLoading()

    //用户访问/admin为前缀的
    let token = getToken()
    if (!token && to.path.startsWith('/admin')){
        showMessage('请先登录', 'warning')
        next({path:'/login'})
    } else if (token && to.path == ('/login')){
        //用户已经登录，且重复访问
        showMessage('请勿重新登录', 'warning')
        //跳转到后台
        next({ path: '/admin/index' })
    } else if (!to.path.startsWith('/admin')) {
        let blogSettingsStore = useBlogSettingsStore()

        blogSettingsStore.getBlogSettings()
        next()
    } else {
        next()
    }
})

// 全局路由后置守卫
router.afterEach((to, from) => {
    // to and from are both route objects.
    //动态设置 Title
    let title = (to.meta.title ? to.meta.title : '') + ' - Weblog'
    document.title = title

    //结束界面加载 Loading
    hidePageLoading()
})